package com.yaorange.web;

import com.yaorange.service.CustomerService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/stats")
public class StatsHandler {

    @Resource
    private CustomerService  customerService;

    @GetMapping("/week-market")
    public Map<String,Object> showWeekMarket(){
        Map<String,Object> result = new HashMap<>();
        List<Map<String,Object>> weekData = customerService.getWeekData();
        //准备存储数据行和标题行集合
        List<String> titles = new ArrayList<>();
        List<Integer> datas = new ArrayList<>();
        for (Map<String, Object> map : weekData) {//{name:"",number:}
            titles.add((String)map.get("name"));
            //mysql默认返回的所有整数类型都为Long类型
            //Oracle默认返回的所有整数类型都为BigDecimal类型
            datas.add(((Long)map.get("number")).intValue());
        }
        //封装返回前端结果
        //{titles:["张三","李四"],datas:[6,2]}
        result.put("titles",titles);
        result.put("datas",datas);
        return result;
    }

    @GetMapping("/year-month-market/{monthValue}")
    public Map<String,Object> showYearAndMonthMarket(@PathVariable String  monthValue){
        List<Map<String, Object>> dataMap = customerService.getYearAndMonthData(2,monthValue);//2代表业务员添加

        Map<String, Object> returnMap = new HashMap<>();

        //准备数据行集合，需要一个map数据
        List<Map<String, Object>> series= new ArrayList<>();

        //准备标题行集合
        List<String> legend = new ArrayList<>();

        //遍历组装返回前端需要的格式
        for (Map<String, Object> dataObj : dataMap) {
            Map<String, Object> data_series = new HashMap<>();
            data_series.put("name",dataObj.get("name"));
            data_series.put("value",((Long)dataObj.get("number")));
            //mysql返回的统计函数数值默认为Long类型
            legend.add((String)dataObj.get("name"));
            series.add(data_series);
        }
        returnMap.put("series",series);
        returnMap.put("legend",legend);
        return returnMap;
    }
}
